package devTools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 身份证分析类
 * @author ChenK 2018-09-26
 */
public class AnalysisIdcard {
    /**
     * 分析生日
     * @param idcard 身份证号
     * @return
     */
    public Date AnalysisBirthday(String idcard) {
        if (idcard.length() < 15) {
            return null;
        }
        String birthday = null;
        Date date = null;
        if (idcard.length() == 18) {
            birthday = idcard.substring(6, 14);
        } else if (idcard.length() == 15) {
            birthday = "19" + idcard.substring(6, 12);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            date = sdf.parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }finally {
            return date;
        }
    }

    /**
     * 分析籍贯
     * @param idcard 身份证号
     * @return
     */
    public String AnalysisNativePlace(String idcard) {
        if (idcard.length() < 15) {
            return null;
        }
        String pref_six = idcard.substring(0, 6);
        NativePlaceCode nativePlaceCode = NativePlaceCode.getInstance();
        return nativePlaceCode.getNativePlace(pref_six);
    }

    /**
     * 分析性别
     * @param idcard 身份证号
     * @return
     */
    public String AnalysisSex(String idcard) {
        if (idcard.length() == 18) {
            return Integer.valueOf(idcard.substring(16, 17)) % 2 == 0 ? "2" : "1";
        } else if (idcard.length() == 15) {
            return Integer.valueOf(idcard.substring(13, 14)) % 2 == 0 ? "2" : "1";
        }
        return null;
    }
}
